'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

interface OrderItem {
  id: number;
  productId: number;
  productName: string;
  productPrice: number;
  quantity: number;
  subtotal: number;
}

interface Order {
  id: number;
  customerId: number;
  customerName: string;
  customerEmail: string;
  customerPhone: string;
  customerAddress: string;
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  cancelReason?: string;
  createdAt: string;
  updatedAt: string;
  items: OrderItem[];
  activities?: Activity[];
}

interface Activity {
  id: number;
  action: string;
  fromStatus?: string;
  toStatus?: string;
  description: string;
  performedBy: string;
  createdAt: string;
}

export default function OrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const [resolvedParams, setResolvedParams] = useState<{ id: string } | null>(null);
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);
  const [error, setError] = useState('');
  const [cancelReason, setCancelReason] = useState('');
  const [showCancelDialog, setShowCancelDialog] = useState(false);
  const router = useRouter();

  useEffect(() => {
    async function resolveParams() {
      const resolved = await params;
      setResolvedParams(resolved);
    }
    resolveParams();
  }, [params]);

  useEffect(() => {
    if (resolvedParams) {
      fetchOrder();
    }
  }, [resolvedParams]);

  const fetchOrder = async () => {
    if (!resolvedParams) return;
    
    try {
      const response = await fetch(`/api/orders/${resolvedParams.id}`);
      if (!response.ok) {
        throw new Error('获取订单信息失败');
      }
      const data = await response.json();
      
      // 获取订单活动记录
      const activitiesResponse = await fetch(`/api/orders/${resolvedParams.id}/activities`);
      if (activitiesResponse.ok) {
        const activitiesData = await activitiesResponse.json();
        data.activities = activitiesData;
      }
      
      setOrder(data);
    } catch (error) {
      console.error('获取订单详情失败:', error);
      setError('获取订单信息失败');
    } finally {
      setLoading(false);
    }
  };

  const updateOrderStatus = async (newStatus: Order['status'], reason?: string) => {
    if (!order) return;
    
    setUpdating(true);
    setError('');
    
    try {
      const requestBody: any = { status: newStatus };
      if (newStatus === 'cancelled' && reason) {
        requestBody.cancelReason = reason;
      }

      const response = await fetch(`/api/orders/${order.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });

      if (!response.ok) {
        const errorData = await response.json();
        setError(errorData.error || '更新订单状态失败');
        return;
      }

      const updatedOrder = await response.json();
      setOrder({ ...order, status: updatedOrder.status, cancelReason: updatedOrder.cancelReason });
      setShowCancelDialog(false);
      setCancelReason('');
      
    } catch (error: any) {
      console.error('更新订单状态失败:', error);
      setError(error.message);
    } finally {
      setUpdating(false);
    }
  };

  const handleCancelClick = () => {
    setShowCancelDialog(true);
  };

  const handleCancelConfirm = () => {
    if (cancelReason.trim()) {
      updateOrderStatus('cancelled', cancelReason.trim());
    } else {
      setError('请填写取消原因');
    }
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      'pending': '待支付',
      'paid': '已支付',
      'shipped': '已发货',
      'delivered': '已交付',
      'cancelled': '已取消'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      'pending': 'bg-yellow-100 text-yellow-800',
      'paid': 'bg-blue-100 text-blue-800',
      'shipped': 'bg-indigo-100 text-indigo-800',
      'delivered': 'bg-green-100 text-green-800',
      'cancelled': 'bg-red-100 text-red-800'
    };
    return colorMap[status as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  const getNextStatusActions = (currentStatus: Order['status']) => {
    const actions = {
      pending: ['paid', 'cancelled'],
      paid: ['shipped', 'cancelled'],
      shipped: ['delivered'],
      delivered: [],
      cancelled: []
    };
    return actions[currentStatus];
  };

  if (loading) return <div className="p-8">加载中...</div>;
  if (!order) return <div className="p-8">订单不存在</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/orders" className="text-gray-600 hover:text-gray-900">
            ← 返回订单列表
          </Link>
          <h1 className="text-3xl font-bold">订单详情</h1>
        </div>
        
        <div className="flex items-center space-x-3">
          <span className={`px-3 py-1 text-sm font-medium rounded-full ${getStatusColor(order.status)}`}>
            {getStatusText(order.status)}
          </span>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 订单信息 */}
        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <h2 className="text-xl font-semibold mb-4">订单信息</h2>
            
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <div className="text-sm text-gray-600">订单号</div>
                <div className="text-lg font-semibold">ORD-{order.id.toString().padStart(6, '0')}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">订单金额</div>
                <div className="text-lg font-semibold text-blue-600">¥{order.totalAmount.toLocaleString()}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">下单时间</div>
                <div className="text-sm font-medium">
                  {new Date(order.createdAt).toLocaleString('zh-CN')}
                </div>
              </div>
              <div>
                <div className="text-sm text-gray-600">最后更新</div>
                <div className="text-sm font-medium">
                  {new Date(order.updatedAt).toLocaleString('zh-CN')}
                </div>
              </div>
            </div>

            {/* 显示取消原因 */}
            {order.status === 'cancelled' && order.cancelReason && (
              <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
                <div className="text-sm font-medium text-red-800 mb-1">取消原因：</div>
                <div className="text-sm text-red-700">{order.cancelReason}</div>
              </div>
            )}

            {/* 状态操作按钮 */}
            {getNextStatusActions(order.status).length > 0 && (
              <div className="border-t pt-4">
                <h3 className="text-sm font-medium text-gray-600 mb-2">订单操作</h3>
                <div className="flex space-x-2">
                  {getNextStatusActions(order.status).map((action) => (
                    <button
                      key={action}
                      onClick={() => action === 'cancelled' ? handleCancelClick() : updateOrderStatus(action as Order['status'])}
                      disabled={updating}
                      className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 disabled:bg-gray-400"
                    >
                      {updating ? '处理中...' : `标记为${getStatusText(action)}`}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 订单商品 */}
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">订单商品</h2>
            
            <div className="space-y-3">
              {order.items.map((item) => (
                <div key={item.id} className="flex justify-between items-center p-3 border border-gray-200 rounded-md">
                  <div className="flex-1">
                    <Link 
                      href={`/products/${item.productId}?from=order&orderId=${order.id}`}
                      className="font-medium text-blue-600 hover:text-blue-800 hover:underline"
                    >
                      {item.productName}
                    </Link>
                    <div className="text-sm text-gray-600">单价: ¥{item.productPrice}</div>
                  </div>
                  <div className="text-right">
                    <div className="font-medium">×{item.quantity}</div>
                    <div className="text-sm text-blue-600">¥{item.subtotal}</div>
                  </div>
                </div>
              ))}
            </div>

            <div className="border-t pt-4 mt-4">
              <div className="flex justify-between items-center text-lg font-semibold">
                <span>订单总计:</span>
                <span className="text-blue-600">¥{order.totalAmount.toLocaleString()}</span>
              </div>
            </div>
          </div>
        </div>

        {/* 客户信息 */}
        <div>
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <h3 className="text-lg font-semibold mb-4">客户信息</h3>
            
            <div className="space-y-3">
              <div>
                <div className="text-sm text-gray-600">客户姓名</div>
                <div className="font-medium">{order.customerName}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">邮箱</div>
                <div className="font-medium">{order.customerEmail}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">电话</div>
                <div className="font-medium">{order.customerPhone}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">地址</div>
                <div className="font-medium">{order.customerAddress}</div>
              </div>
            </div>

            <div className="mt-4 pt-4 border-t">
              <Link
                href={`/customers/${order.customerId}`}
                className="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-center block"
              >
                查看客户详情
              </Link>
            </div>
          </div>

          {/* 订单活动记录 */}
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <h3 className="text-lg font-semibold mb-4">订单活动记录</h3>
            
            <div className="space-y-3 max-h-60 overflow-y-auto">
              {order.activities && order.activities.length > 0 ? (
                order.activities.map((activity) => (
                  <div key={activity.id} className="p-3 border border-gray-200 rounded-md">
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="font-medium text-sm">{activity.description}</div>
                        {activity.fromStatus && activity.toStatus && (
                          <div className="text-xs text-gray-600 mt-1">
                            {getStatusText(activity.fromStatus)} → {getStatusText(activity.toStatus)}
                          </div>
                        )}
                      </div>
                      <div className="text-right">
                        <div className="text-xs text-gray-500">
                          {new Date(activity.createdAt).toLocaleString('zh-CN')}
                        </div>
                        <div className="text-xs text-gray-400">
                          {activity.performedBy}
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center text-gray-500 py-4">
                  暂无活动记录
                </div>
              )}
            </div>
          </div>

          {/* 快速操作 */}
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-lg font-semibold mb-4">快速操作</h3>
            
            <div className="space-y-3">
              <button className="w-full px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                发送订单确认邮件
              </button>
              <button className="w-full px-4 py-2 bg-yellow-600 text-white rounded-md hover:bg-yellow-700">
                打印订单
              </button>
              <button className="w-full px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">
                导出订单PDF
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 取消订单对话框 */}
      {showCancelDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96">
            <h3 className="text-lg font-semibold mb-4">取消订单</h3>
            
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                取消原因
              </label>
              <textarea
                value={cancelReason}
                onChange={(e) => setCancelReason(e.target.value)}
                placeholder="请输入取消订单的原因..."
                className="w-full p-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                rows={3}
              />
            </div>

            {error && (
              <div className="mb-4 p-2 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
                {error}
              </div>
            )}

            <div className="flex justify-end space-x-3">
              <button
                onClick={() => {
                  setShowCancelDialog(false);
                  setCancelReason('');
                  setError('');
                }}
                className="px-4 py-2 text-gray-600 hover:text-gray-800"
              >
                取消
              </button>
              <button
                onClick={handleCancelConfirm}
                disabled={updating || !cancelReason.trim()}
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:bg-gray-400"
              >
                {updating ? '处理中...' : '确认取消'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}